using System;

namespace Storage.Core
{
	internal class ReadByIdResponse : IStorageResponse
	{
		public ReadByIdResponse(PlainEntity result)
		{
			Result = result;
		}

		public byte[] Serialize()
		{
			FastBinarySerializer serializer;
			if (Result == null)
			{
				serializer = new FastBinarySerializer(4);
				serializer.Write(false);
				return serializer.Buffer;
			}

			int serializedSize = sizeof(byte) + sizeof(Int32) + Result.EstimatedSerializedSize();
			serializer = new FastBinarySerializer(serializedSize, serializedSize);
			serializer.Write(StorageOpCodes.ReadById);
			serializer.Write(true);
			serializer.Write(Result);
			return serializer.Buffer;
		}

		public static ReadByIdResponse Deserialize(byte[] content)
		{
			var deserializer = new FastBinaryDeserializer(content, 1);
			return !deserializer.ReadBool() 
				? new ReadByIdResponse(null) 
				: new ReadByIdResponse(PlainEntity.Deserialize(deserializer));
		}

		public PlainEntity Result { get; private set; }
	}
}